package com.heima.comment.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.UserFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    GreenScan greenScan;
    @Autowired
    UserFeign userFeign;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    ArticleFeign articleFeign;
    @Autowired
    CommentHotService commentHotService;

    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
        //1 校验参数
        //   校验文章id   校验size
        if ((dto.getSize() == null || dto.getSize() == 0)) {
            dto.setSize(10);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        //   ========================需要变更处 start =============================
        //2 查询Mongo文章所有评论列表
        List<ApComment> apCommentList = new ArrayList<>();
        if (dto.getIndex().intValue() == 1) { // 判断当前是否是首页评论
            // 先查询热点评论集合  （最多5条） (条件: flag=1, 文章id, 点赞降序)
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("flag").is(1));
            query.limit(5);
            Sort sort = Sort.by(Sort.Direction.DESC, "likes");
            query.with(sort);
            //热点评论
            List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);


            // 新size = size - 热评数量
            int newSize = dto.getSize() - apComments.size();
            // 查询第一页剩余普通评论 (条件: 文章id, flag=0, 时间降序, limit:新size)
            Query ordinaryQuery = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("createdTime").lt(dto.getMinDate()));
            ordinaryQuery.limit(newSize);
            Sort ordinarySort = Sort.by(Sort.Direction.DESC, "createdTime");
            ordinaryQuery.with(ordinarySort);

            //普通评论
            List<ApComment> commentList = mongoTemplate.find(ordinaryQuery, ApComment.class);
            // 合并 热点评论  普通评论   热点list.addAll(普通list)
            for (ApComment apComment : apComments) {
                apCommentList.add(apComment);
            }
            for (ApComment apComment : commentList) {
                apCommentList.add(apComment);
            }

        } else {
            // 不是第一页直接查询普通评论
            // (条件: 文章id,flag=0,createdTime小于最小时间,时间降序,limit:size)
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("createdTime").lt(dto.getMinDate()));
            //   (文章id  , 创建时间 小于最小时间 , 截取size条记录 , 创建时间降序)
            query.limit(dto.getSize());
            Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
            query.with(sort);
            List<ApComment>  allOrdinaryComment= mongoTemplate.find(query, ApComment.class);
            for (ApComment apComment : allOrdinaryComment) {
                apCommentList.add(apComment);
            }
        }
        // ========================需要变更处 end =============================
        //3 封装查询结果
        //3.1 用户未登录 直接返回评论列表
        if (user==null){
            return ResponseResult.okResult(apCommentList);
        }
        //3.2 用户登录，需要加载当前用户对评论点赞的列表
        ArrayList<ApCommentVo> apCommentVos = new ArrayList<>();
        for (ApComment apComment : apCommentList) {
            Query userLikeQuery = Query.query(Criteria.where("commentId").is(apComment.getId())
                    .and("authorId").is(user.getId()));
            ApCommentLike apCommentLike = mongoTemplate.findOne(userLikeQuery, ApCommentLike.class);
            //   将每一个评论  ApComment 转成 ApCommentVO
            ApCommentVo apCommentVo = new ApCommentVo();
            BeanUtils.copyProperties(apComment,apCommentVo);
            //  其中  如果当前评论id在点赞记录中存在  设置operation字段为0  不存在不用做任何处理
            if (apCommentLike!=null){
                apCommentVo.setOperation((short)0);
            }
            apCommentVos.add(apCommentVo);
        }

        return ResponseResult.okResult(apCommentVos);
    }

    @Override
    public ResponseResult like(CommentLikeDTO dto) {
        //1. 参数校验
        //   评论id不能为空  operation必须为 0  或  1
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2. 根据评论id查询  评论数据， 为null返回错误信息
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));

        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3. 如果是点赞操作 判断是否已经点赞
        Query likeQuery = Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentId()));
        if (0 == dto.getOperation()) {
            ApCommentLike apCommentLike = mongoTemplate.findOne(likeQuery, ApCommentLike.class);
            //判断是否已经点赞
            if (apCommentLike != null) {
                //   点过赞提示 请勿重复点赞
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿重复点赞");

            } else {
                //   未点过赞   保存点赞信息到mongo
                ApCommentLike commentLike = new ApCommentLike();
                commentLike.setAuthorId(user.getId());
                commentLike.setCommentId(dto.getCommentId());
                commentLike.setOperation((short) 0);
                mongoTemplate.save(commentLike);

                //   并修改评论信息的点赞数量( + 1)
                apComment.setLikes(apComment.getLikes()+1);
                mongoTemplate.save(apComment);
            }
        } else {
            //4. 如果是取消点赞操作
            //   删除点赞信息
            mongoTemplate.remove(likeQuery, ApCommentLike.class);

            //  并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
            Integer likes = apComment.getLikes();
            if (likes >= 1) {
                apComment.setLikes(apComment.getLikes()-1);
                mongoTemplate.save(apComment);
            }
        }

        //调用计算热点评论方法
        commentHotService.hotCommentExecutor(apComment);


        //5. 返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
        ApComment comment = mongoTemplate.findOne(query, ApComment.class);
        Integer likes = comment.getLikes();
        Map<String, Object> map = new HashMap<>();
        map.put("likes", likes);

        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        //1. 校验参数
        //   校验是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //   校验文章id   校验内容不为空  校验内容长度不能大于140个字符 (validated校验)

        try {
            //2. 阿里云校验评论内容是否违规
            ScanResult scanResult = greenScan.greenTextScan(dto.getContent());

            //   过滤掉违规词汇：替换为**
            String filteredContent = scanResult.getFilteredContent();

            //3. 远程查询当前登陆用户信息
            ResponseResult<ApUser> userById = userFeign.findUserById(user.getId());
            if (!userById.checkCode()) {
                CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
            }
            ApUser apUser = userById.getData();

            //根据传入的文章Id远程调用获取文章信息
            ResponseResult<ApArticle> articleById = articleFeign.findArticleById(dto.getArticleId());
            if (!articleById.checkCode()) {
                CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
            }
            ApArticle apArticle = articleById.getData();

            //4. 创建评论信息，并保存到mongo
            ApComment apComment = new ApComment();
            apComment.setAuthorId(apUser.getId());
            apComment.setAuthorName(apUser.getName());
            apComment.setArticleId(dto.getArticleId());
            apComment.setType((short) 0);//评论内容类型  0文章  1动态
            apComment.setChannelId(apArticle.getChannelId());
            if (filteredContent != null) {
                apComment.setContent(filteredContent);
            } else {
                apComment.setContent(dto.getContent());
            }
            apComment.setImage(apUser.getImage());
            apComment.setLikes(0);//点赞量
            apComment.setReply(0);//回复量
            apComment.setFlag((short) 0);//0普通评论 1热点评论 2推荐评论 3置顶评论 4精品评论 5大V评论
            apComment.setLongitude(new BigDecimal("0"));
            apComment.setLatitude(new BigDecimal("0"));
            apComment.setAddress("");
            apComment.setOrd(0);
            apComment.setCreatedTime(new Date());
            apComment.setUpdatedTime(new Date());

            mongoTemplate.save(apComment);

        } catch (Exception e) {
            log.info("保存评论时出现异常", e.getCause());
            e.printStackTrace();
        }

        return ResponseResult.okResult();
    }
}
